//
//  StatusListModel.swift
//  SwiftStory
//
//  Created by ZxjMacBookPro on 2020/6/11.
//  Copyright © 2020 ZxjMacBookPro. All rights reserved.
//

import UIKit
import SDWebImage

class StatusListModel: UIView {
    ///保存微博数据
    var statuses: [StatusViewModel]?
    
    ///获取微博数据
    func loadData(lastStatus: Bool, finished: @escaping (_ models: [StatusViewModel]?, _ error: NSError?)->())
        {
            var since_id = statuses?.first?.status.idstr ?? "0"
            var max_id = "0"

            if lastStatus {
                since_id = "0"
                max_id = statuses?.last?.status.idstr ?? "0"
            }

            NetWorkTools.sharInstance.loadStatuses(since_id: since_id, max_id: max_id) { (array, error) in
                // 1.安全校验
                if error != nil
                {
                    finished(nil, error)
                    return
                }
                guard let arr = array else
                {
                    return
                }
                
                // 2.将字典数组转换为模型数组
                var statusModels = [Status]()
                var models = [StatusViewModel]()

                statusModels = Status.mj_objectArray(withKeyValuesArray: arr) as! [Status]
                
                for status in statusModels{
                    let viewModel = StatusViewModel(status: status)
                    models.append(viewModel)
                }
                
                // 3.保存微博数据
    //            self.statuses = models
                if since_id != "0" {
                    self.statuses = models + self.statuses!
                }else if max_id != "0" {
                    self.statuses = self.statuses! + models
                }else{
                    self.statuses = models
                }
                self.cachesImages(viewModels: models, finished: finished)
            }
        }
    
        private func cachesImages(viewModels: [StatusViewModel], finished: @escaping (_ models: [StatusViewModel]?, _ error: NSError?)->()) {
            let group = DispatchGroup()
            
            for viewModel in viewModels {
                
                ///从模型中取出配图数组
                guard let picurls = viewModel.thumbnail_pic else {
                    continue
                }
                
                for url in picurls {
                    group.enter()
                    
                    SDWebImageDownloader.shared.downloadImage(with: url) { (image, data, error, _) in
                        group.leave()
                        SDImageCache.shared.storeImage(toMemory: image, forKey: url.absoluteString)
                        NSLog(message: "图片下载完成 + \(url)")
                    }
                
                }
  

            }
            group.notify(queue: DispatchQueue.main) {
                NSLog(message: "图片缓存完成")
                    finished(viewModels, nil)
            }
        }

}
